import Cookies from 'js-cookie'
import { getLanguage } from '@/lang/index'
import Vue from 'vue'

const state = {
  sidebar: {
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  },
  device: 'desktop',
  language: getLanguage(),
  size: Cookies.get('size') || 'small',
  showChangePwdDialog: false,
  showChangePwdClose: true,
  // 未读消息数量
  unreadMessageCount: 0
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      Cookies.set('sidebarStatus', 1)
    } else {
      Cookies.set('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    Cookies.set('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  SET_LANGUAGE: (state, language) => {
    state.language = language
    Cookies.set('language', language)
  },
  SET_SIZE: (state, size) => {
    state.size = size
    Cookies.set('size', size)
  },
  SET_SHOW_CHANGE_PWD_DIALOG: (state, flag) => {
    state.showChangePwdDialog = flag
  },
  SET_SHOW_CHANGE_PWD_CLOSE: (state, flag) => {
    state.showChangePwdClose = flag
  },
  // 设置未读消息数量
  SET_UNREAD_MESSAGE_COUNT: (state, count) => {
    state.unreadMessageCount = count
  }
}

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  setLanguage({ commit }, language) {
    commit('SET_LANGUAGE', language)
  },
  setSize({ commit }, size) {
    commit('SET_SIZE', size)
  },
  setShowChangePwdDialog({ commit }, flag) {
    commit('SET_SHOW_CHANGE_PWD_DIALOG', flag)
  },
  setShowChangePwdClose({ commit }, flag) {
    commit('SET_SHOW_CHANGE_PWD_CLOSE', flag)
  },
  setUnreadMessageCount({ commit }, count) {
    commit('SET_UNREAD_MESSAGE_COUNT', count)
  },
  // 未读消息数量相关处理
  // 加1
  increaseUnreadMessageCount(context) {
    const count = context.state.unreadMessageCount
    context.commit('SET_UNREAD_MESSAGE_COUNT', count + 1)
  },
  // 减1
  decreaseUnreadMessageCount(context) {
    const count = context.state.unreadMessageCount
    if (count > 0) {
      context.commit('SET_UNREAD_MESSAGE_COUNT', count - 1)
    }
  },
  // 清零
  setUnreadMessageCountEqaulZero(context) {
    context.commit('SET_UNREAD_MESSAGE_COUNT', 0)
  },
  // 初始化，从后端服务中读取
  initUnreadMessageCount(context) {
    Vue.prototype.$api.support.message.getUnreadMessageCount()
      .then(res => {
        context.commit('SET_UNREAD_MESSAGE_COUNT', res.data)
      })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
